package com.tinyengine.it.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Collections;

@Component
public class JwtTokenUtil {

    @Value("${jwt.secret:yZ7ipIEbhi22otwBZzhnWkMNaQCx9dkyCQwkfOhegzZb3WzByHoKNjOsDJYYKMYuL7pwc2WywoeelfAX0GZRZ7QVQXu8T3KrQbRaEruLWQfoyT0RpCYNIcefD94rZDml0dYl7Z9KbdCjqNnb0igcGrNMeEhqIvZtu5E4zzU22MnkU1yx1gIyS9pXDZXwjXqf39f7Udrj9PZxD2SigfmAUSRWZm4OCtImi2nyyXmw1XXUz9h2ocm3SBqnvYiUSeUc}")
    private String secret;

    @Value("${jwt.expiration:86400000}")
    private Long expiration;

    // 用于存储已失效的token
    private final Set<String> invalidatedTokens = Collections.synchronizedSet(new HashSet<>());

    private Key getSigningKey() {
        byte[] keyBytes = secret.getBytes();
        return Keys.hmacShaKeyFor(keyBytes);
    }

    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return createToken(claims, userDetails.getUsername());
    }

    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    public void invalidateToken(String token) {
        invalidatedTokens.add(token);
    }

    public boolean isTokenInvalidated(String token) {
        return invalidatedTokens.contains(token);
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token) && !isTokenInvalidated(token));
    }

    public String getUsernameFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    private Date getExpirationDateFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getExpiration();
    }
} 